<?php

namespace app\tours\controller;

class User extends Common {

        /**
         * @登陆页面
         */
        public function login() {
                if (IS_POST) {
                        $username = I('post.username');
                        $password = I('post.password');
                        if ($username && $password) {
                                $where = array();
                                $where['mobile|email'] = $username;
                                $where['password'] = pwSha($password);
                                $user = D("User")->field(true)->relation(true)->where($where)->find();
                                if (empty($user)) {
                                        return $this->error("用户名或密码错误！");
                                } else {
                                        M("User")->where(array('id' => $user['id']))->setField(array('login_ip' => get_client_ip(), 'login_time' => time()));
                                        if (!empty($user['realname'])) {
                                                $userName = $user['username'];
                                        } else {
                                                $userName = $user['username'];
                                        }

                                        session('uid', $user['id']);
                                        session('username', $userName);
                                        cookie('uid', $user['id']);
                                        cookie('username', $userName);
                                        if (I('post.cooktime') == "1") {
                                                cookie('auth_key', array('uid' => $user['id'], 'key' => pwSha($user['id'])), 30 * 24 * 60 * 60);
                                        }
                                        $last_url = session('last_url');

                                        if ($last_url) {
                                                session('last_url', null);
                                                return $this->success("", $last_url);
                                        } else {
                                                return $this->success("", U('/user/index', '', '', false, true));
                                        }
                                }
                        } else {
                                return $this->error("请填写用户名或密码~！");
                        }
                } else {
                        $uid = session('uid');
                        if (!empty($uid)) {
                                return $this->redirect(U('User/index'));
                        }
                }

                return $this->fetch();
        }

        /**
         * @快速登录
         */
        public function quicklogin() {
                if (IS_POST) {
                        $actionName = I('post.actionName');
                        $username = I('post.username');
                        $password = I('post.password');
                        if ($username && $password) {
                                $where = array();
                                $where['mobile|email'] = $username;
                                $where['password'] = pwSha($password);
                                $user = M("User")->field("id,username,password")->where($where)->find();
                                if (empty($user)) {
                                        $this->assign('error', "用户名或密码错误！");
                                } else {
                                        M("User")->where(array('id' => $user['id']))->setField(array('login_ip' => get_client_ip(), 'login_time' => time()));
                                        session('uid', $user['id']);
                                        session('username', $user['username']);
                                        cookie('uid', $user['id']);
                                        cookie('username', $user['username']);
                                        echo '<script type="text/javascript">document.domain = "' . C("site.sitedomain") . '";parent.' . $actionName . '();parent.closeEditor();</script>';
                                }
                        }
                }
                return $this->fetch();
        }

        /**
         * @注册页面
         */
        public function register() {
                if (IS_POST) {
                        //超过3次
                        if (session('email_num') >= 3)
                                $this->error('发件次数超过限制！请明日再试。');

                        $email = I('post.email');
                        $mobile = I('post.mobile');
                        $verify = new \org\Verify();
                        if (empty($email) || empty($mobile))
                                return $this->error("手机或邮箱不能为空！");

                        if (!isMobile($mobile) || !isEmail($email))
                                return $this->error("手机或邮箱格式不正确");

                        if (!$verify->check(I('post.verify'), "tours")) {
                                return $this->error("验证码错误!");
                        }


                        $auth = authcode($email . "&" . $mobile, 'ENCODE', 24 * 3600);
                        $url = U('user/regpassword', array('auth' => $auth), 'html', 'www');
                        $this->assign('username', $mobile);
                        $this->assign('url', $url);
                        $this->assign('email', $email);
                        $body = $this->fetch("public/email_register");
                        $return = send_mail($email, $mobile, C('site.sitename') . "会员注册验证", $body);
                        if ($return === true) {
                                session('email', $email);
                                session('email_num', session('email_num') + 1);
                                return $this->success("恭喜，操作成功，注册邮件1封，3秒后送达！");
                        } else {
                                return $this->error($return);
                        }
                } else {
                        $email_num = session("email_num");
                        $this->assign('email_num', $email_num);
                        $emails = session('email');
                        $email_array = explode('@', $emails);
                        if (!empty($email_array) && is_array($email_array)) {
                                if (!empty($email_array[1])) {
                                        $email_address = 'http://mail.' . $email_array[1];
                                } else {
                                        $email_address = 'http://mail.' . '';
                                }
                                $this->assign('email_address', $email_address);
                        }
                        $this->assign('emails', $emails);
                        return $this->fetch();
                }
        }

        /**
         * @快速注册
         */
        public function quickRegister() {
                if (IS_POST) {
                        $mobile = I('post.mobile');
                        $email = I('post.email');
                        $string = new \org\String;
                        $password = $string::rand_string(6, 1);
                        $this->assign('mobile', $mobile);
                        $this->assign('password', $password);
                        $this->assign('email', $email);
                        $body = $this->fetch("public/email_quickregister");
                        $user = D("User");
                        if ($user->create()) {
                                $data['email'] = $email;
                                $data['mobile'] = $mobile;
                                $data['password'] = pwSha($password);
                                $data['username'] = '新会员';
                                $data['regedit_ip'] = get_client_ip();
                                $data['regedit_time'] = NOW_TIME;
                                $data['login_time'] = NOW_TIME;
                                $uid = $user->add($data);
                                if ($uid) {
                                        session("uid", $uid);
                                        $username = $user->where(array('id' => $uid))->getField("username");
                                        session('username', $username);
                                        cookie('uid', $uid);
                                        cookie('username', $username);
                                        send_mail($email, $mobile, C('site.sitename') . "会员注册验证", $body);
                                } else {
                                        return $this->error();
                                }
                                return $this->success("操作成功！");
                        } else {
                                return $this->error();
                        }
                        return $this->fetch('quicklogin');
                }
        }

        /**
         * 注册验证
         */
        public function realtion() {
                $name = I('post.name');
                switch ($name) {
                        case "mobile":
                                $mobile = I('post.param');
                                if (M("User")->where(array('mobile' => $mobile))->getField("id")) {
                                        $this->ajaxReturn("", "手机号已经存在！", "n");
                                } else {
                                        $this->ajaxReturn("", "正确", "y");
                                }
                                break;
                        case "email":
                                $email = I('post.param');
                                if (M("User")->where(array('email' => $email))->getField("id")) {
                                        $this->ajaxReturn("", "邮箱已经存在！", "n");
                                } else {
                                        $this->ajaxReturn("", "正确", "y");
                                }
                        case "verify":

                                $this->ajaxReturn("", "正确", "y");
                                break;
                        default:

                                break;
                }
        }

        /**
         * 下一步操作
         */
        public function QuickNext() {
                if (IS_POST) {
                        $actionName = I('post.actionName');
                        if (!empty($actionName))
                                echo '<script type="text/javascript">document.domain = "' . C("site.sitedomain") . '";parent.' . $actionName . '();parent.closeEditor();</script>';
                        return $this->fetch('quicklogin');
                }
        }

        /**
         * @快速注册验证
         */
        public function quickrealtion() {
                $name = I('name');
                switch ($name) {
                        case "mobile":
                                $mobile = I('param');
                                if (M("User")->where(array('mobile' => $mobile))->getField("id")) {
                                        $this->ajaxReturn("", "该手机已注册过，请在左侧登陆！", "n");
                                } else {
                                        $this->ajaxReturn("", "正确", "y");
                                }
                                break;
                        case "email":
                                $email = I('param');
                                if (M("User")->where(array('email' => $email))->getField("id")) {
                                        $this->ajaxReturn("", "该邮箱已注册过，请在左侧登陆！", "n");
                                } else {
                                        $this->ajaxReturn("", "正确", "y");
                                }
                        default:

                                break;
                }
        }

        /**
         * 录入注册信息
         */
        public function regpassword() {
                $auth = I('get.auth');
                $auth = authcode($auth, 'DECODE');
                $auth = explode("&", $auth);
                $user = D("User");
                if (IS_AJAX) {
                        $validate = \think\Loader::validate('User');
                        if (!$validate->scene('add')->check($_REQUEST)) {
                                return $this->error($validate->getError());
                        }
                        if ($user->create()) {
                                $data['email'] = $_POST['email'];
                                $data['mobile'] = $_POST['mobile'];
                                $data['password'] = pwSha($_POST['password']);
                                $data['username'] = '新会员';
                                $data['regedit_ip'] = get_client_ip();
                                $data['regedit_time'] = NOW_TIME;
                                $data['login_time'] = NOW_TIME;
                                $data['email_check'] = 1;
                                $uid = $user->add($data);
                                if ($uid) {
                                        session("uid", $uid);
                                        $username = '新会员';
                                        session('username', $username);
                                        cookie('uid', $uid);
                                        cookie('username', $username);
                                        return $this->success("注册成功！，倒数3个数，进入个人中心！", '', U('/user/index', '', '', false, true), '3');
                                } else {
                                        return $this->error($user->getError());
                                }
                        } else {
                                return $this->error($user->getError());
                        }
                } else {
                        if (!isEmail($auth[0]) && !isMobile($auth[1])) {
                                return $this->error("非法链接");
                        }
                        $email = $auth[0];
                        $mobile = $auth[1];
                        $this->assign('email', $email);
                        $this->assign('mobile', $mobile);
                        return $this->fetch();
                }
        }

        /**
         * @后台首页
         */
        public function index() {
                $this->checkUser();
                //取出会员信息
                $uid = session('uid');
                $user = D("User")->field(true)->relation(true)->find($uid);
                $this->assign('user', $user);
                //判断是否绑定邮箱和手机
                $security_hd = 0;
                $user['email_check'] == 1 ? $security_hd+=1 : "";
                $user['mobile_check'] == 1 ? $security_hd+=1 : "";
                $this->assign('security_hd', $security_hd);
                //取出个人订单
                $order = D('ToursOrder');
                $where['uid'] = $uid;
                $where['is_del'] = 0;
                $list = $order->relation(true)->where($where)->order('create_time desc')->limit(8)->select();
                $this->assign('list', $list);

                //推荐产品
                $tuijian = D("Tours")->field(true)->cache()->where(array('ispreference' => 1, 'ischecked' => 1, 'isnotshow' => 0, 'isdelete' => 0))->order("dateline desc")->limit(4)->select();
                $this->assign("tuijian", $tuijian);

                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @线路订单
         */
        public function orderline() {
                $this->checkUser();
                $uid = session('uid');
                $order = D('ToursOrder');
                $where['uid'] = $uid;
                $where['is_del'] = 0;
                $count = $order->where($where)->count();
                $page = new \org\Page($count, 10, "", "");
                $list = $order->relation(true)->where($where)->order('create_time desc')->limit($page->firstRow . "," . $page->listRows)->select();
                $this->assign("page", trim($page->show()));
                $this->assign('list', $list);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @线路订单删除
         */
        public function orderline_del($id = "") {
                $this->checkUser();
                $data['is_del'] = 1;
                $result = M("ToursOrder")->where(array('id' => $id))->save($data);
                if ($result) {
                        return $this->success();
                } else {
                        return $this->error(M("ToursOrder")->getError());
                }
        }

        /**
         * @个人资料
         */
        public function info() {
                $this->checkUser();
                $model = M("UserInfo");
                $uid = session('uid');
                $user_info = $model->field(true)->find($uid);
                if (IS_POST) {
                        if ($model->create()) {
                                if (strlen(I("realname")) > 20) {
                                        $this->error("名字超过长度限制！");
                                }
                                $data['user_id'] = session('uid');
                                $data['birthday'] = I("year") . '-' . I("month") . '-' . I("day");
                                $data['realname'] = I('post.realname');
                                $data['sex'] = I('post.sex');
                                if (empty($user_info)) {
                                        $model->add($data);
                                } else {
                                        $model->where(array('user_id' => $uid))->save();
                                }

                                M("User")->where(array('id' => $uid))->setField('username', I("username"));


                                $this->success("基本资料修改成功！");
                        }
                } else {
                        $userInfo = D("UserInfo")->relation(true)->field(true)->find(session('uid'));
                        if (!empty($userInfo['birthday'])) {
                                $birthday = explode('-', $userInfo['birthday']);
                                $userInfo['year'] = $birthday[0];
                                $userInfo['month'] = $birthday[1];
                                $userInfo['day'] = $birthday[2];
                        } else {
                                $userInfo['year'] = date('Y');
                                $userInfo['month'] = date('m');
                                $userInfo['day'] = date('d');
                        }
                        if (!empty($userInfo['sex'])) {
                                $userInfo['sex'] = $userInfo['sex'];
                        } else {
                                $userInfo['sex'] = '';
                        }
                        $this->assign('userinfo', $userInfo);
                        $uid = session('uid');
                        if (!empty($uid)) {
                                return $this->fetch();
                        }
                }
        }

        /**
         * @账户安全
         */
        public function security() {
                $this->checkUser();
                $uid = session("uid");
                $user = M("User")->field("email,email_check,mobile,mobile_check")->find($uid);
                $this->assign('user', $user);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @修改密码
         */
        public function password() {
                $this->checkUser();
                $uid = session('uid');
                if (IS_AJAX) {
                        $OldPassword = I('OldPassword');
                        $NewPassword = I('userpassword');
                        if (pwSha($OldPassword) != M("User")->where(array('id' => $uid))->getField('password')) {
                                return $this->error("原密码输入错误！");
                        }
                        if (trim($NewPassword) == "") {
                                return $this->error("新密码不能为空！");
                        }
                        M("User")->where(array('id' => $uid))->setField("password", pwSha($NewPassword));

                        session(null);
                        cookie("auth_key", null);
                        cookie("uid", null);
                        cookie("username", null);
                        cookie(null);
                        return $this->success("密码修改成功，请重新登陆", U('/tour/user/login', '', '', false, true));
                } else {
                        $uid = session('uid');
                        if (!empty($uid)) {
                                return $this->fetch();
                        }
                }
        }

        /**
         * @绑定邮箱
         */
        public function emailvalidate() {
                $this->checkUser();
                $auth = I('get.auth');
                $uid = session('uid');
                if ($auth) {
                        $auth = authcode($auth, 'DECODE');
                        $auth = explode("&", $auth);
                        if ($uid == $auth[1]) {
                                M("User")->where(array('id' => $uid))->setField(array('email' => $auth[0], 'email_check' => 1));
                                $step = 2;
                                $this->assign('email', $auth[0]);
                        } else {
                                $this->error("非法链接");
                        }
                } else {
                        $email = M("User")->where(array('id' => $uid))->getField('email');
                        $this->assign('email', $email);
                        $step = 1;
                }
                $this->assign('step', $step);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @发送邮件
         */
        public function SendValidateEmail() {
                $this->checkUser();
                $uid = session('uid');
                //超过3次
                if (session('email_num') >= 3)
                        $this->error('threeError');
                //邮箱已存在
                if (IS_AJAX) {
                        $email = I("txtEmail");
                }
                $check = M("User")->where(array('email' => $email, 'id' => array('neq', $uid)))->find();
                if ($check) {
                        $this->error('exists');
                }
                $username = session('username');
                $auth = authcode($email . "&" . $uid, 'ENCODE', 24 * 3600);
                $url = U('user/emailvalidate', array('auth' => $auth), 'html', 'www');
                $this->assign('username', $username);
                $this->assign('url', $url);
                $this->assign('email', $email);
                $body = $this->fetch("public/email_validate");
                $return = send_mail($email, $username, C('site.sitename') . "会员验证提醒", $body);
                if ($return === true) {
                        M("User")->where(array('id' => $uid))->setField(array('email_check' => 0));
                        session('email_num', session('email_num') + 1);
                        return $this->success("success");
                } else {
                        return $this->error($return);
                }
        }

        /**
         * @我的收藏
         */
        public function cline() {
                $this->checkUser();

                $userlineModel = D('UserLine');
                $c_data['uid'] = session('uid');

                $count = $userlineModel->where($c_data)->count();
                $page = new \org\Page($count, 10, "", "");
                $userline = $userlineModel->where($c_data)->limit($page->firstRow, $page->listRows)->select();
                $this->assign('page', trim($page->show()));
                $this->assign('userline', $userline);
                //猜你喜欢  最新推荐线路  

                $Tours = D("Tours");
                $tuijian = $Tours->field(true)->cache()->where(array('isgood' => 1, 'ischecked' => 1, 'isnotshow' => 0, 'isdelete' => 0))->order("dateline desc")->limit(4)->select();
                $this->assign('tuijian', $tuijian);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @删除收藏产品
         */
        public function cline_del($id = "") {
                $this->checkUser();
                M("UserLine")->where(array('id' => $id,))->delete();
                return $this->success();
        }

        /**
         * @我的资讯
         */
        public function mycounsel() {
                $this->checkUser();
                $uid = session('uid');

                $model = D("ToursCounsel");
                $count = $model->where(array('uid' => $uid))->count();
                $page = new \org\Page($count, 10, "", "");
                $consel = $model->relation(true)->where(array('uid' => $uid))->limit($page->firstRow, $page->listRows)->select();
                $this->assign('page', trim($page->show()));
                $this->assign('consel', $consel);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @回复我的
         */
        public function myreply() {
                $this->checkUser();
                $uid = session('uid');
                $model = D("ToursCounsel");
                $count = $model->where(array('uid' => $uid, 'reply' => array('neq', "")))->count();
                $page = new \org\Page($count, 10, "", "");
                $consel = $model->relation(true)->where(array('uid' => $uid, 'reply' => array('neq', "")))->limit($page->firstRow, $page->listRows)->select();
                $this->assign('page', trim($page->show()));
                $this->assign('consel', $consel);
                $uid = session('uid');
                if (!empty($uid)) {
                        return $this->fetch();
                }
        }

        /**
         * @退出登陆
         */
        public function loginout() {
                session(null);
                cookie("auth_key", null);
                cookie("uid", null);
                cookie("username", null);
                cookie(null);
                $this->redirect("/");
        }

        /**
         * @找回密码1
         */
        public function findpassword() {
                $email_num = session("email_num");
                $this->assign('email_num', $email_num);
                return $this->fetch();
        }

        /**
         * @找回密码2（发件）
         */
        public function SendEmailForFindPassword() {
                //超过3次
                if (session('email_num') >= 3)
                        $this->error('threeError');

                $email = I('post.username');
                $username = session("username");
                $auth = authcode($email, 'ENCODE', 24 * 3600);
                $url = U('user/EmailFindPasswordReset', array('auth' => $auth), 'html', 'www');
                $this->assign('url', $url);
                $this->assign('email', $email);
                $body = $this->fetch("public/email_password");
                $return = send_mail($email, $username, C('site.sitename') . "重置密码确认邮件", $body);
                if ($return === true) {
                        session('email_num', session('email_num') + 1);
                        return $this->success($email);
                } else {
                        return $this->error($return);
                }
        }

        /**
         * @找回密码3（重置）
         */
        public function EmailFindPasswordReset() {
                $auth = I('get.auth');
                $email = authcode($auth, 'DECODE');
                $check = M("User")->where(array('email' => $email))->find();
                if (empty($check)) {
                        $this->redirect("user/findpassword");
                }
                $this->assign('email', $email);
                return $this->fetch();
        }

        /**
         * @找回密码最后一步
         */
        public function ResetPassword() {
                if (IS_AJAX) {
                        $newEmail = I("email");
                        $newPassword = I('newpassword');
                        if ($newEmail && $newPassword) {
                                M("User")->where(array('email' => $newEmail))->setField("password", pwSha($newPassword));
                                return $this->success("密码修改成功，请重新登陆", U('user/login', '', '', false, true));
                        }
                } else {
                        return $this->error("页面不存在！", C('site.siteurl'));
                }
        }

}
